package ru.ipo.dces.plugins.admin;

import ru.ipo.dces.client.Controller;
import ru.ipo.dces.clientservercommunication.GetUserHistoryRequest;
import ru.ipo.dces.clientservercommunication.GetUserHistoryResponse;
import ru.ipo.dces.plugins.admin.resultstable.MapTableCellRenderer;
import ru.ipo.dces.plugins.admin.resultstable.OneMessageTableModel;
import ru.ipo.dces.plugins.admin.resultstable.CenteredTextTableCellRenderer;
import ru.ipo.dces.plugins.admin.resultstable.UserHistoryTableModel;
import ru.ipo.dces.server.ServerFailReason;
import ru.ipo.dces.utils.ResponseHandler;

import javax.swing.*;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: ilya
 * Date: 30.03.11
 * Time: 11:55
 */
public class UserHistoryDisplay extends JPanel {

    private JTable table;

    private static MapTableCellRenderer renderer = new MapTableCellRenderer();

    static {
        renderer.setEmptyText("Пока не проверено");
        renderer.setSubstituteRenderer(true);
    }

    public UserHistoryDisplay() {
        this.add(new JScrollPane(table = new JTable()));

        table.setDefaultRenderer(Map.class, renderer);
        table.setDefaultRenderer(Integer.class, new CenteredTextTableCellRenderer());
    }

    private int userID = -1;

    public int getUserID() {
        return userID;
    }

    public void setUserID(int userID) {
        this.userID = userID;
    }

    public void updateInfo() {
        //change model
        ResponseHandler<GetUserHistoryResponse> handler = new ResponseHandler<GetUserHistoryResponse>() {
            @Override
            public void success(GetUserHistoryResponse response) {
                table.setModel(new UserHistoryTableModel(response.historyLines));
            }

            @Override
            public void fail(ServerFailReason exception) {
                if (exception.getExceptionType() == ServerFailReason.ServerExceptionType.ServerReturnedError)
                    setError("Ошибка: " + exception.getMessage());
                if (exception.getExceptionType() == ServerFailReason.ServerExceptionType.GeneralRequestFailureException)
                    setError("Не удалось связаться с сервером");
            }
        };

        GetUserHistoryRequest r = new GetUserHistoryRequest();
        r.sessionID = Controller.getContestConnection().getSessionID();
        r.userID = userID;
        r.sendSubmissions = false;
        r.fromId = -1;
        r.toId = -1;
        Controller.doRequest(r, handler, "Получение истории соревнования");
    }

    private void setError(String message) {
        table.setModel(new OneMessageTableModel(message));
    }
}
